package com.pengchuang.ACS.face.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.pengchuang.ACS.admin.api.feign.UserFeignClient;
import com.pengchuang.ACS.common.constant.GlobalConstants;
import com.pengchuang.ACS.common.entity.UserEntity;
import com.pengchuang.ACS.common.enums.RecordEnums;
import com.pengchuang.ACS.common.utils.FeignUtil;
import com.pengchuang.ACS.common.utils.R;
import com.pengchuang.ACS.common.utils.ResultCode;
import com.pengchuang.ACS.face.entity.CellEntity;
import com.pengchuang.ACS.face.entity.DoorEntity;
import com.pengchuang.ACS.face.entity.RecordEntity;
import com.pengchuang.ACS.face.entity.TempEntity;
import com.pengchuang.ACS.face.service.CellService;
import com.pengchuang.ACS.face.service.DoorService;
import com.pengchuang.ACS.face.service.RecordService;
import com.pengchuang.ACS.face.service.TempService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @description:
 * @projectName: AccessControlSystem
 * @see: com.pengchuang.ACS.face.controller
 * @author: pc
 * @createTime: 2023/3/22 13:25
 * @version: 1.0
 */
@RequestMapping("/qrcode")
@RestController
public class QrController {

	@Autowired
	public TempService tempService;

	@Autowired
	public RecordService recordService;

	@Autowired
	public DoorService doorService;

	@Autowired
	public CellService cellService;

	@Autowired
	public UserFeignClient userFeignClient;


	@GetMapping("/gen_qrcode/{authCode}")
	public void qrCodeGen(HttpServletResponse response, @PathVariable String authCode) throws Exception {

		// 查看对应的授权码
		DoorEntity doorEntity = doorService.getBaseMapper().selectOne(new QueryWrapper<DoorEntity>().eq("auth_code", authCode));
		if (doorEntity == null) {
			return;
		}

		// context是二维码里面的内容，如果是网址则会跳转到网址界面
		String uuid = IdUtil.randomUUID();
		// 保存临时数据 生成二维码数据
		// 获取用户username进行保存
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		Object username = request.getAttribute("username");

		TempEntity tempEntity = new TempEntity();
		// 测试用户名
		if (username == null) {
			username = "test";
		} else {
			// 调用微服务查询用户信息，以及对应的门禁终端机id
			tempEntity.setCellId(doorEntity.getCellId());
			tempEntity.setDoorId(doorEntity.getId());
		}


		tempEntity.setUsername(String.valueOf(username));
		tempEntity.setTempUuid(uuid);
		tempService.save(tempEntity);
		QrConfig config = new QrConfig(300, 300);
		config.setImg(GlobalConstants.FILEPATH + "logo.png");


		//设置输出流内容格式为图片格式
		response.setContentType("image/jpeg");
		//response的响应的编码方式为utf-8
		response.setCharacterEncoding("utf-8");
		QrCodeUtil.generate(GlobalConstants.MAIN_URL_PATH + "valid_qrcode/" + uuid,
				config,
				"jpg",
				response.getOutputStream());
	}

	/**
	 * 验证二维码
	 * @param code
	 * @throws Exception
	 */
	@GetMapping("/valid_qrcode/{code}")
	public R qrCodeValid(@PathVariable String code) throws Exception {
		// 查看对应授权码
		TempEntity tempEntity = tempService.getBaseMapper().selectOne(new QueryWrapper<TempEntity>().eq("temp_uuid", code));
		if (tempEntity == null) {
			return R.error(ResultCode.DOOR_NO_AUTH);
		}
		// 查看创建时间进行相对应设置
		if (tempEntity.getCreateTime().getTime() > (new Date().getTime() - 1000 * 60 * 60)) {
			// 查询对应的小区信息
			CellEntity cellEntity = cellService.getById(tempEntity.getCellId());
			// 查询对应的小区门禁信息
			DoorEntity doorEntity = doorService.getById(tempEntity.getDoorId());

			// 获取用户详细信息
			R userByUsername = userFeignClient.getUserByUsername(tempEntity.getUsername());
			if (!"200".equals(userByUsername.get("code"))) {
				return R.error();
			}
			UserEntity userEntity = FeignUtil.convertValue(userByUsername.get("result"), UserEntity.class);
			// 记录通行记录
			recordService.save(RecordEntity.builder().cellId(cellEntity.getId())
					.cellName(cellEntity.getCellName())
					.doorId(doorEntity.getId())
					.doorName(doorEntity.getDoorName())
					.status(1)
					.uid(userEntity.getId())
					.username(userEntity.getUsername())
					.nickname(userEntity.getNickname())
					.type(RecordEnums.QR_USER.getType())
					.userType(RecordEnums.QR_USER.getUserType()).build());
			// 返回认证成功
			return R.ok();
		}
		// 返回错误
		return R.error();

	}
}
